'use strict';

import gulp from 'gulp';
import babel from 'gulp-babel';
import autoprefixer from 'gulp-autoprefixer';
import uglify from 'gulp-uglify';
import browserSync from 'browser-sync';
import includeTag from 'gulp-include-tag'; //include 方法
import sass from 'gulp-sass';
import minifycss from 'gulp-minify-css';
import rename from 'gulp-rename';

//error 后，的操作，用于less报错后继续执行
import plumber from 'gulp-plumber';

// browserify 编译 ES6
import browserify from 'browserify';
// 创建map
import sourcemaps from 'gulp-sourcemaps';

// gulp 中使用的是 vinyl-buffer  browserify 中使用的是 普通的 buffer 需要转换下
import source from 'vinyl-source-stream';
import buffer from 'vinyl-buffer';
import babelify from 'babelify';

import { cssPath, sassPath, jsPath, htmlPath, entryFiles } from './source.js';

function prod(){
    var reload = browserSync.reload;

    gulp.task('cssbuild', () => {
      gulp.src(cssPath)
        .pipe( autoprefixer({browsers: ['last 2 versions','Firefox >= 20']}) )
        .pipe(minifycss())  
        .pipe(rename({
            dirname:'assets/css',
            extname: '.build.css'
        }))
        .pipe(gulp.dest('build/'))
    })

    gulp.task('sassbuild', function () {
        gulp.src(sassPath)
            .pipe(sass())
            .pipe(autoprefixer({browsers: ['last 2 versions','Firefox >= 20']}) )
            .pipe(minifycss()) 
            .pipe(rename({
                dirname:'assets/css',
                extname: '.build.css'
            }))
            .pipe(gulp.dest('build/'))
    });

    //任务 - include 方法 
    /**
    *  eg: <include src="public/header.html" data="test"></include>
    *  在header.html可以通过 {{data}} 获取到test
    */
    gulp.task('includebuild', () => {
      gulp.src(htmlPath)
        .pipe(plumber())
        .pipe(includeTag())
        .pipe(gulp.dest('build'))
    });

    //set browserify task - JS异步刷新 这里用到了map缓存
    gulp.task('es6build',()=> {
        const tasks = entryFiles.map(function(entry){
            return browserify({
                entries: entry,
                debug: false
            })
            .transform("babelify", {presets: ["es2015"]})
            .bundle()// 多个文件打包成一个文件
            .on('error', function(err){
              console.log(err.message);
              this.emit('end');
            })
            .pipe(source(entry))// browserify的输出不能直接用做gulp输入，所以需要source进行处理 
            .pipe(rename({
                dirname:'assets/js',
                extname: '.build.js'
            }))
            .pipe(buffer()) //需要转换成buffer，才能继续其他操作
            .pipe(uglify())
            .pipe(gulp.dest('build/'))
        })
    
        // return es.merge.apply(null, tasks);
    })

    gulp.task('build', ['cssbuild','sassbuild','includebuild','es6build','uibuild']);
}

export default prod;